﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Linq;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Columns;

namespace QuanLyTiemThuocTay.GUI
{
    public partial class frmQLNguoiDung : DevExpress.XtraEditors.XtraForm
    {
        QLTTDataContext db = new QLTTDataContext();

        public frmQLNguoiDung()
        {
            InitializeComponent();
        }

        private void frmQLNguoiDung_Load(object sender, EventArgs e)
        {
            gc.DataSource = new BindingList<NGUOIDUNG>(db.NGUOIDUNGs.ToList());
            btDong.ImageList = btLamTuoi.ImageList = btThem.ImageList = icon;
        }

        private void btDong_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void gv_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            var rownew = e.Row as NGUOIDUNG;
            var rowold = db.NGUOIDUNGs.SingleOrDefault(x => x.MaNguoiDung == rownew.MaNguoiDung);
            if (rowold!=null)
            {
                rowold = rownew;
                db.SubmitChanges();
                clsHam.HienThi(Text, "Cập nhật thành công!");
            }
            else
            {
                db.NGUOIDUNGs.InsertOnSubmit(rownew);
                db.SubmitChanges();
                clsHam.HienThi(Text, "Thêm mới thành công!");
            }
        }

        private void gv_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
            (sender as GridView).ShowEditor();
        }

        private void btThem_Click(object sender, EventArgs e)
        {
            gv.AddNewRow();
            gv.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gv.FocusedColumn = gv.VisibleColumns[0];
            gv.ShowEditor();
        }

        private void gv_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.SetRowCellValue(e.RowHandle, view.Columns["MaNguoiDung"], 0);
            view.SetRowCellValue(e.RowHandle, view.Columns["NamSinh"], DateTime.Now.AddYears(-20));
            view.SetRowCellValue(e.RowHandle, view.Columns["GioiTinh"], true);
            view.SetRowCellValue(e.RowHandle, view.Columns["MatKhau"], clsHam.MaHoa("VietNam"));
            view.SetRowCellValue(e.RowHandle, view.Columns["LaQuanLy"], false);
            view.SetRowCellValue(e.RowHandle, view.Columns["ConLamViec"], true);
        }

        private void btXoa_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var row = gv.GetRow(gv.GetSelectedRows()[0]) as NGUOIDUNG;
            if (MessageBox.Show(String.Format("Bạn chắc chắn xóa người dùng: {0}?", row.HoVaTen), "Xác nhận xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question)==DialogResult.Yes)
            {
                try
                {
                    db.NGUOIDUNGs.DeleteOnSubmit(row);
                    db.SubmitChanges();
                    gv.DeleteRow(gv.GetSelectedRows()[0]);
                    gv.RefreshData();
                    clsHam.HienThi(Text, "Xóa thành công");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Không thể xóa người dùng này. \n Phục hồi thông tin. " + Environment.NewLine + "Lỗi: " + ex.Message, "Không thể xóa", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void gv_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            ColumnView view = sender as ColumnView;
            GridColumn col = view.Columns["HoVaTen"];
            string hovaten = view.GetRowCellValue(e.RowHandle, col) as string;
            if (hovaten == null) hovaten = "";
            if (hovaten.Equals(String.Empty)||hovaten.Length<2)
            {
                e.Valid = false;
                view.SetColumnError(col, "Phải dài hơn 2 ký tự");
                gv.FocusedColumn = col;
                (sender as GridView).ShowEditor();
            }

            GridColumn col2 = view.Columns["TenDangNhap"];
            string tendn = view.GetRowCellValue(e.RowHandle, col) as string;
            if (tendn == null) tendn = "";
            if (tendn.Equals(String.Empty) || tendn.Length < 2)
            {
                e.Valid = false;
                view.SetColumnError(col2, "Phải dài hơn 2 ký tự");
                gv.FocusedColumn = col2;
                (sender as GridView).ShowEditor();
            }

            var mand = Int32.Parse(view.GetRowCellValue(e.RowHandle, (sender as GridView).Columns["MaNguoiDung"]).ToString());
            var tontai = db.NGUOIDUNGs.Where(x => x.HoVaTen == tendn.Trim()).FirstOrDefault();
            if (tontai!=null)
            {
                if (mand==0 || tontai.MaNguoiDung != mand)
                {
                    e.Valid = false;
                    view.SetColumnError(col, "Lỗi: Người dùng này đã có trong hệ thống");
                    gv.FocusedColumn = col;
                    (sender as GridView).ShowEditor();
                    return;
                }
            }
        }

        private void btLamTuoi_Click(object sender, EventArgs e)
        {
            gc.DataSource = null;
            gc.RefreshDataSource();
            gc.DataSource = new BindingList<NGUOIDUNG>(db.NGUOIDUNGs.ToList());
            gc.RefreshDataSource();
        }
    }
}